package com.crp.redis.service.impl;

import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.crp.redis.dao.RedisDao;
import com.crp.redis.service.IRedisService;

@Service
public class RedisService implements IRedisService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisDao redisDao;

    public static final String LINK_STR = "_";

    @Override
    public void setObjectForHash(String tablePrefix, String tableType, String field, Object value) {
        String key = this.getHashKey(tablePrefix, tableType);
        redisDao.setJsonStrForHash(key, field, value);

        if (logger.isDebugEnabled()) {
            logger.debug("将key={} field={} value={} 存入redis", key, field, value);
        }
    }

    @Override
    public <T> T getObjectFromHash(String tablePrefix, String tableType, String field, Class<T> clazz) {
        String key = this.getHashKey(tablePrefix, tableType);
        return redisDao.getObjectFromHash(key, field, clazz);
    }

    @Override
    public Map<String, Object> queryEntriesByKey(String tablePrefix, String tableType) {
        String key = this.getHashKey(tablePrefix, tableType);
        return redisDao.getEntriesByHashKey(key);
    }

    @Override
    public void removeObjectsByKeys(String tablePrefix, String tableType, Object... hashKeys) {
        String key = this.getHashKey(tablePrefix, tableType);
        redisDao.removeObjectsBykey(key, hashKeys);
    }

    @Override
    public void setExpireObjectForHash(String tablePrefix, String tableType, String field, Object value, Long timeout) {
        String key = this.getHashKey(tablePrefix, tableType);
        redisDao.setExpireJsonStrForHash(key, field, value, timeout);
    }

    @Override
    public Set<String> queryFields(String tablePrefix, String tableType) {
        String key = this.getHashKey(tablePrefix, tableType);
        return redisDao.queryFieldsByHashKey(key);
    }

    private String getHashKey(String tablePrefix, String tableType) {
        return tablePrefix + LINK_STR + tableType;
    }
}
